<!--
 * @Description: 生产批次查询
-->
<template>
  <BaseMainSlot>
    <!-- <template v-slot:tab-box>
      <label>批次类型:</label>
      <SelectButton :buttonselectlist="batchTypeList" @nowselectbuttonindex="batchChange" />
    </template> -->
    <template v-slot:search-box>
      <SearchForm :formConfig="formConfig" :formData="searchlist" @search="search"
        @getPlantVarietyList="getPlantVarietyList"></SearchForm>
    </template>
    <template v-slot:btn-box>
      <SelectButton :buttonselectlist="buttonselectlist" @nowselectbuttonindex="batchstaumet" />
      <ActionBar
        :page-no="23"
        :has-add="false"
        :has-del="false"
        :has-edit="false"
        :has-cancel="false"
        :has-edit-column="true"
        :has-export="true"
        @showColumn="showColumn"
        @download="download"
      />
    </template>
    <template v-slot:table-box>
      <Table @sortChange="changeTableSort" :propList="tableColumn" v-loading="loading"
        :listData="tableData" :showSelectColumn="false">
        <template v-slot:facilities="{ row, item }">
          <template v-if="!row.index && row.batchId">
            <el-button
              class="text-btn-cursor"
              type="text"
              size="small"
              @click="checkFacility(row, item.prop)"
            >
              <i class="el-icon-view"></i> 查看
            </el-button>
          </template>
        </template>
        <template v-slot:cycle="{ row }">
          <template v-if="!row.index && row.batchId">
            <span v-if="row.cycle || row.plantingPeriodType">
              {{ row.plantingPeriodType == 'SEASONS' ? '多季作物' : row.cycle + "天" }}
            </span>
            <template v-else>—</template>
          </template>
        </template>
        <template v-slot:area="{ row }">
          <template v-if="!row.index && row.batchId">
            {{ row.area }}{{ row.areaUnitName }}
          </template>
        </template>
        <template v-slot:assetValue="{ row }">
          <template v-if="!row.index && row.batchId">
            {{ row.assetValue }}{{ row.assetUnitName }}
          </template>
        </template>
        <template v-slot:lesseeName="{ row, item }">
          <template v-if="!row.index && row.batchId">
            {{ row[item.prop] || "—" }}
          </template>
        </template>
      </Table>
      <Pagination
        :page-size="pageSize"
        :current-page="currentPage"
        :total-size="totalSize"
        @changePageSize="changePageSize"
        @changeCurrentPage="changeCurrentPage"
      />
    </template>
    <template v-slot:dialog>
      <el-dialog :title="facilityDialogType == 'facility' ? '设施列表' : '编号列表'" :visible="facilityDialogVisible"
        class="dialogRec" :before-close="()=>{facilityDialogVisible = false}">
        <div class="facility-list">
          <div v-for="(item,index) in batchFacilityMapperList" :key="index" class="facility-item">
            <div v-if="facilityDialogType == 'facility'" class="info-line">
              <div class="name">设施编号：</div><div class="value">{{ item.facilityNo }}</div>
            </div>
            <div v-if="facilityDialogType == 'facility'" class="info-line">
              <div class="name">设施名称：</div><div class="value">{{ item.facilityName }}</div>
            </div>
            <div v-else class="info-line">
              <div class="name">编号：</div><div class="value">{{ item }}</div>
            </div>
          </div>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="facilityDialogVisible = false">
            关 闭
          </el-button>
        </div>
      </el-dialog>
      <el-dialog
        id="tableColumnDialog"
        title="配置列"
        :visible.sync="dialogTableColumnVisible"
      >
        <tableColumn
          v-if="dialogTableColumnVisible"
          ref="tableColumn"
          :tableColumn="allTableColumn"
          :pathsuffix="batchType"
          @cancelColumn="cancelColumn"
        />
        <div slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="dialogTableColumnVisible = false">
            取 消
          </el-button>
          <el-button
            class="zh-button-two"
            type="primary"
            @click="saveColumn"
          >
            保 存
          </el-button>
        </div>
      </el-dialog>
    </template>
  </BaseMainSlot>
</template>

<script>
import SearchForm from '@/components/searchForm';
import Table from '@/components/table/table.vue';
import ActionBar from "@/components/ActionBar";
import Pagination from "@/components/Pagination";
import nowpagereq from "@/api/digital-production/production-batch-manage/production-batch-query/index";
import unitreq from "@/api/basic-info-manage/unit-manage/index";
import zhongyangleibie from "@/api/basic-info-manage/category-management/index";
// 查询条件
import nowstage from "@/api/digital-production/growth-record-management/growth-stage-division/index";
import tenantInfo from "@/api/digital-operation/tenant-manage/tenant-info/index";
// import agriculturalReport from "@/api/digital-production/statistical-report/agricultural-report";
import userreq from "@/api/user/index";
// import StartTimeEndTimeSelectionBox from "@/components/StartTimeEndTimeSelectionBox";

import BaseMainSlot from "@/components/BaseMainSlot/newBaseMainSlot.vue";
import SelectButton from "@/components/selectbutton/index.vue";
// import BaseMainSlot from "@/components/BaseMainSlot/shangxia.vue"
import { mymixin } from "@/utils/mixin";
import { getToken } from "@/utils/auth";
// import { getToken } from '@/utils/auth';
export default {
  name: "ProductionBatchQuery",
  components: {
    SearchForm,
    Table,
    ActionBar,
    Pagination,
    BaseMainSlot,
    SelectButton,
    // StartTimeEndTimeSelectionBox
  },
  mixins: [mymixin],
  data() {
    return {
      batchType: 0,
      batchTypeList: [{ name: "批次管理" }, { name: "单个管理" }],
      tableColumn: [
        { prop: 'batchName', label: '批次名称', minWidth: '200' },
        { prop: 'batchNo', label: '批次号', minWidth: '150' },
        { prop: 'facilities', label: '种植设施', slotName: 'facilities', minWidth: '110' },
        { prop: 'mode', label: '种植方式', minWidth: '110' },
        { prop: 'plantingTypeName', label: '种植类别', minWidth: '110' },
        { prop: 'varietyName', label: '种植品种', minWidth: '110' },
        { prop: 'cycle', label: '种植周期', slotName: 'cycle', minWidth: '110' },
        { prop: 'area', label: '种植规模', slotName: 'area', minWidth: '110' },
        { prop: 'assetDate', label: '投产日期', minWidth: '110' },
        { prop: 'assetValue', label: '投产量', slotName: 'assetValue', minWidth: '110' },
        { prop: 'lesseeName', label: '承租户', slotName: 'lesseeName', minWidth: '110' },
        // { prop: 'completionDays', label: '花费时间', minWidth: '110' },
        { prop: 'completionDate', label: '完成日期', minWidth: '110' },
      ],
      tableColumn2: [
        { prop: 'batchName', label: '批次名称', minWidth: '200' },
        { prop: 'batchNo', label: '批次号', minWidth: '150' },
        { prop: 'facilities', label: '种植设施', slotName: 'facilities', minWidth: '110' },
        { prop: 'mode', label: '种植方式', slotName: 'lesseeName', minWidth: '110' },
        { prop: 'plantingTypeName', label: '种植类别', minWidth: '110' },
        { prop: 'varietyName', label: '种植品种', minWidth: '110' },
        { prop: 'cycle', label: '种植周期', slotName: 'cycle', minWidth: '110' },
        { prop: 'batchNum', label: '种植数量', minWidth: '110' },
        { prop: 'singleNos', label: '单个编号', slotName: 'facilities', minWidth: '110' },
        { prop: 'assetDate', label: '种植日期', minWidth: '110' },
        { prop: 'lesseeName', label: '承租户', slotName: 'lesseeName', minWidth: '110' },
      ],
      formConfig: [
        {
          label: '批次名称',
          prop: 'batchName',
          type: 'input',
        }, {
          label: '批次号',
          prop: 'batchNo',
          type: 'select',
          options: [], // allbatchList
          optionKey: { label: 'batchName', value: 'batchNo' },
        }, {
          label: '设施名称',
          prop: 'facilityNo',
          type: 'select',
          options: [], // facilyelList
          optionKey: { label: 'facilityName', value: 'facilityNo' }
        }, {
          label: '承租户',
          prop: 'lesseeNo',
          type: 'select',
          options: [], // lesseeList
          optionKey: { label: 'lesseeName', value: 'lesseeNo' }
        }, {
          label: '种植类别',
          prop: 'selectplantlist',
          type: 'cascader',
          options: [], // planttypeList
          change: 'getPlantVarietyList',
          optionKey: {
            expandTrigger: 'hover',
            value: 'plantTypeNo',
            children: 'children',
            label: 'plantTypeName',
            checkStrictly: true
          }
        }, {
          label: '种植品种',
          prop: 'plantVarietyNo',
          type: 'select',
          options: [], // plantVarietyList
          optionKey: { label: 'plantVarietyName', value: 'plantVarietyNo' }
        }, {
          label: '投产日期',
          prop: 'date',
          type: 'daterange',
        },
      ],
      buttonselectlist: [{ name: "未完成批次" }, { name: "已完成批次" }],
      // 一般为农业类型id
      farmingTypeNo: "",
      // 所有批次
      allbatchList: [
        // { value: '这是啥' }
      ],
      // searchName: "",
      // 当前生产批次完成状态
      nowbatchstau: 0,
      // 种养类别
      planttypeList: [],
      selectplantlist: "",
      // 当前表格选择的数组
      nowSelectList: [],
      organizationNo: "",
      // 下拉框数据
      lesseeList: [],
      plantVarietyList: [],
      // 查询条件
      batchNo: "",
      facilityNo: "",
      lesseeNo: "",
      plantVarietyNo: "",

      // 所搜索框内容
      searchlist: {},

      facilyelList: [],
      batchFacilityMapperList: [],
      facilityDialogVisible: false,
      facilityDialogType: ''
    };
  },
  watch: {},
  created() {
    this.tableColumn1 = [ ...this.tableColumn ]
    this.search();
  },
  mounted() {
    this.getselectdatalist();
    this.getBatchList();
  },
  methods: {
    // 批次类型切换
    batchChange(i) {
      if (i === 0) {
        this.tableColumn = [...this.tableColumn1]
        this.allTableColumn = [...this.tableColumn1]
      } else {
        this.tableColumn = [...this.tableColumn2]
        this.allTableColumn = [...this.tableColumn2]
      }
      this.batchType = i
      this.tableData = [];
      this.getBatchList();
      this.loadSaveColumn()
      this.search();
    },
    checkFacility(row, prop) {
      if (row.batchNo) {
        if (prop == 'facilities') {
          this.facilityDialogType = 'facility'
          this.batchFacilityMapperList = row.batchFacilityMapperList || [];
        } else {
          this.facilityDialogType = 'singleNos'
          this.batchFacilityMapperList = row.singleNos?.split(',') || [];
        }
        this.facilityDialogVisible = true;
      }
    },
    // // 搜索框模糊查询方法
    // querybatchSearch (queryString, cb) {
    //   var restaurants = this.allbatchList;
    //   var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
    //   // 调用 callback 返回建议列表的数据
    //   cb(results);
    // },
    // createFilter (queryString) {
    //   return (restaurant) => {
    //     return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
    //   };
    // },
    // 获取单位名称
    async getUnitByCondition(id) {
      let unitName = "斤";
      await unitreq.getUnitByCondition(id).then(res => {
        if (res.data[0]) {
          unitName = res.data[0].unitName;
        }
      });
      return unitName;
    },
    // 在有农业类型的页面中以此方法为获取表格方法
    // chancefarmtype(e) {
    //   this.farmingTypeNo = e
    //   // 获取表格数据
    //   this.search();
    // },
    // 条件查询所有批次
    getBatchList() {
      // 条件查询所有批次
      let partwo = {
        organizationNo: getToken('organizationNo'),
        farmingTypeNo: getToken('farmingTypeNo'),
        batchType: this.batchType === 0 ? 'BATCH' : 'SINGLE',
        simpleData: true
      }
      nowpagereq.querybylist(partwo).then(
        restwo => {
          let listtwo = restwo.data
          this.allbatchList = listtwo
          this.formConfig[1].options = listtwo;
        }
      )
    },
    // 获取下拉框数据
    async getselectdatalist() {
      // 获取种养类别树状表
      zhongyangleibie.getplantingTypeTree().then(res => {
        let list = res.data;
        this.planttypeList = list;
        this.formConfig[4].options = res.data;
      });

      // 做不同的请求获取数据
      // 获取承租人下拉框
      const { data: lessee } = await tenantInfo.queryLessesByCondition();
      this.lesseeList = lessee;
      this.formConfig[3].options = lessee;
      userreq
        .getfacilityAll({
          organizationNo: sessionStorage.getItem("organizationNo"),
          // organizationNoList: sessionStorage.getItem("organizationList").split(","),
          farmingTypeNo: sessionStorage.getItem("farmingTypeNo"),
          facilityStatus: false
        })
        .then(res => {
          this.facilyelList = res.data;
          this.formConfig[2].options = res.data
        });
      this.getPlantVarietyList();
    },
    //  获取品种名称
    getPlantVarietyList(param) {
      let params = {
        plantTypeNo: param?.selectplantlist[0]
      };
      this.plantVarietyNo = "";
      nowstage.getPlantVariety(params).then(res => {
        if (res.code !== 1) {
          return;
        }
        this.plantVarietyList = res.data;
        this.formConfig[5].options = res.data;
      });
    },
    startVal(e) {
      this.$set(this.searchlist, "startTime", e);
    },
    endVal(e) {
      this.$set(this.searchlist, "endTime", e);
    },
    // 生产批次查询
    batchstaumet(i) {
      this.nowbatchstau = i;
      if (this.batchType == 0) {
        let len = this.tableColumn.length - 1
        this.tableColumn[len].hide = i === 0
      }
      this.tableData = [];
      this.search();
    },
    // 导出
    async download() {
      let params = {
        entity: {
          ...this.entity,
        }
      }
      let url = 'v3/batch/productionBatch/download'
      let excel = '生产批次表'
      this.downloadExcel(url, params, excel)
    },
    // 表格查询
    getTableDataList() {
      this.loading = true;
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        sortList: this.sortList || [],
        entity: {
          batchName: this.searchlist.batchName,
          batchType: this.batchType === 0 ? 'BATCH' : 'SINGLE',
          deleteFlag: false,
          batchNo: this.searchlist.batchNo,
          lesseeNo: this.searchlist.lesseeNo,
          farmingTypeNo: getToken("farmingTypeNo"),
          organizationNo: getToken("organizationNo"),
          status: this.nowbatchstau,
          plantingTypeNo: this.searchlist.selectplantlist && this.searchlist.selectplantlist[0],
          varietyNo: this.searchlist.plantVarietyNo,
          facilityNo: this.searchlist.facilityNo,
          // assetDate: this.searchlist.assetDate
          startTime: this.searchlist.date && this.dateToFormattwo(this.searchlist.date[0]),
          endTime: this.searchlist.date && this.dateToFormattwo(this.searchlist.date[1]),
        }
      };
      this.entity = params.entity
      nowpagereq.gettablelist(params).then(res => {
        this.loading = false;
        if (res.code === 1) {
          // this.$message.success('查询成功')
        } else {
          this.$message.error("查询失败");
        }
        let data = res.data.content;
        this.tableData = data;
        // 赋值总条数
        this.totalSize = res.data.totalElements;
        this.addblankmet();
        this.resetActionBar();
      });
      // 判断搜索输入框数据
    },
    search() {
      this.currentPage = 1;
      this.getTableDataList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.getTableDataList();
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.getTableDataList();
    },
    handleEdit(row) {
      if (row.id) {
        this.formData = row;
        this.editActive = true;
        this.saveActive = false;
        this.cancelActive = true;
        this.canInput = false;
      }
    },
    handleSelectionChange(list) {
      this.nowSelectList = [];
      this.nowSelectList = list.map(item => item.batchNo);
      if (this.nowSelectList.length === 1) this.delActive = true;
      else this.delActive = false;
    }
  }
};
</script>

<style scoped lang="scss">
.facility-list {
  display: flex;
  justify-content: flex-start;
  flex-direction: row;
  flex-wrap: wrap;
  .facility-item {
    width: 400px;
    max-width: 30%;
    min-width: 30%;
    margin-right: 3%;
    margin-bottom: 10px;
    // height: 80px;
    border-radius: 5px;
    // border: 1px solid #ccc;
    box-shadow: 1px 1px 10px rgba(0, 0, 0, 0.15);
    padding: 10px 20px;

    .info-line {
      display: flex;
      justify-content: flex-start;
      align-items: flex-start;
      font-size: 14px;
      &:not(:last-child) {
        margin-bottom: 10px;
      }
      .name {
        text-align: left;
        width: 80px;
        flex-shrink: 0;
      }
      .value {
        width: 100%;
        text-align: left;
        font-weight: normal;
      }
    }
  }
}
::v-deep .tab-select {
  width: 100%;
  .butt-list-sty {
    position: absolute;
    left: 5px;
    top: 7px;
  }
}
</style>
